/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.htiiot.activemq.jaas;

import java.io.IOException;
import java.security.Principal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.auth.login.FailedLoginException;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;

import com.htiiot.activemq.db.DbConnectionPool;
import com.htiiot.activemq.db.JDBCUtils;
import com.htiiot.activemq.dbConfig.DbConfig;

public class RdbmsLoginModule implements LoginModule {


	private Subject subject;
	private CallbackHandler callbackHandler;

	private boolean debug;
	private Set<Principal> principals = new HashSet<Principal>();
	private boolean loginSucceeded;
	private DbConnectionPool pool;

	/**
	 * 初始化
	 */
	@Override
	public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) {
		loginSucceeded = false;
		this.subject = subject;
		this.callbackHandler = callbackHandler;

		String url = (String) options.get("url");
		String dbPassword = (String) options.get("password");

		String dbUser = (String) options.get("user");
		String driverClass = (String) options.get("driver");
		debug = "true".equalsIgnoreCase((String) options.get("debug"));
		//初始化数据库链接
		
		DbConfig config = new DbConfig(url, dbUser, dbPassword, driverClass);
		pool = DbConnectionPool.getPool(config );

	}

	@Override
	public boolean login() throws LoginException {
		NameCallback nameCb = new NameCallback("Username: ");
		PasswordCallback passCb = new PasswordCallback("Password: ", false);
		Callback[] callbacks = new Callback[] { nameCb, passCb };
		try {
			callbackHandler.handle(callbacks);
		} catch (IOException ioe) {
			throw new LoginException(ioe.getMessage());
		} catch (UnsupportedCallbackException uce) {
			throw new LoginException(uce.getMessage() + " not available to obtain information from user");
		}
		String user = nameCb.getName();
		char[] tmpPassword = passCb.getPassword();
		if (tmpPassword == null) {
			tmpPassword = new char[0];
		}
		if (user == null) {
			throw new FailedLoginException("user name is null");
		}
		
		//校验
		loginSucceeded = rdbmsValidate(user, new String(tmpPassword));
		
		return loginSucceeded;
	}
	
	/**
	 * 从数据库取出密码，并校验密码
	 * @param username
	 * @param password
	 * @return
	 * @throws SQLException
	 */
	private boolean rdbmsValidate(String username, String password) {
		
		boolean validated = false;
		
		 String sql = "select * from test where username=?";
	        Connection conn = pool.getConnection();
	        PreparedStatement ps = null;
	        ResultSet rs = null;
	        try {
	            ps = conn.prepareStatement(sql);
	            ps.setString(1, username);
	            rs = ps.executeQuery();
	            while (rs.next()) {
	                String dPass = rs.getString("pass");
	                if(dPass!=null&&dPass.equals(password)){
	                	validated = true;
	                	break;
	                }
	            }
	        } catch (SQLException e) {
	         //   throw e;
	        } finally {
	            JDBCUtils.close(ps, rs, conn);
	        }
		
		
		return validated;
	}

	@Override
	public boolean commit() throws LoginException {
		boolean result = loginSucceeded;
		return result;
	}

	@Override
	public boolean abort() throws LoginException {
		clear();

		if (debug) {
			// LOG.debug("abort");
		}
		return true;
	}

	@Override
	public boolean logout() throws LoginException {
		subject.getPrincipals().removeAll(principals);
		principals.clear();
		clear();
		if (debug) {
			// LOG.debug("logout");
		}
		return true;
	}

	private void clear() {
		loginSucceeded = false;
	}
}
